import './Visual.css';

import { Component } from 'react';
import React from 'react';

class VisualHelper extends Component{
  constructor(props){
    super(props);

    this.state = {
      showHelper        : props.visual.showHelper,
      sortedByGroup     : true,
      groupedAttributes : [],
      columns           : 3,
    };

    this.attributes = [];

    this.updateVisual        = this.updateVisual.bind(this);
    this.handleButtonClicked = this.handleButtonClicked.bind(this);
    this.handleValueChanged  = this.handleValueChanged.bind(this);
    
    this.updateButton       = React.createRef();
    this.refreshButton      = React.createRef();
  }

  componentDidMount(){
    this.initAttributes();
    this.updateRate = 100;
    const interval = setInterval(this._autoRefresh.bind(this), this.updateRate);
    this.interval = interval;
  }

  componentWillUnmount(){
    clearInterval(this.interval);
  }

  // 自动刷新
  _autoRefresh(){
    this.initAttributes();
  }

  // 初始化属性
  initAttributes(){
    const visual = this.props.visual;
    let attributes = [];

    for(var key in visual.attributes){
      const newAttribute = {
        key      :key, 
        value    :visual.attributes[key].value, 
        type     :visual.attributes[key].type, 
        group    :visual.attributes[key].group,
        readOnly :visual.attributes[key].readOnly,
      }
      attributes.push(newAttribute);
    }
    this.attributes = attributes;

    const groupedAttributes = this.groupAttributes(attributes, this.state.columns);

    // console.log('属性值：', attributes);
    this.setState({
      // attributes        : attributes,
      groupedAttributes : groupedAttributes
    });
  }
  // 分组属性
  groupAttributes(attributes, columns){
    let groupsDict = {};
    attributes.forEach((attribute)=>{

      const group = attribute.group;
      if(group in groupsDict){
        groupsDict[group].push(attribute);
      }
      else{
        groupsDict[group]=[attribute];
      }
    })

    let groupedAttributes = [];
    for(let group in groupsDict){
      groupedAttributes.push({group:group, children:groupsDict[group]});
    }
    // console.log('Grouped:', groupedAttributes);

    columns = parseInt(columns);

    const rows = [];
    var i = 0, il = 0;
    for(i = 0, il=groupedAttributes.length; i < il; i += columns){
      var row = [];
      for(var j = 0; j < columns && (i + j) < il; j ++){
        row.push(groupedAttributes[i + j]);
      }
      rows.push(row);
    }
    groupedAttributes = rows;
    return groupedAttributes;
  }
  handleButtonClicked(event){
    const key = event.target.id;
    const visual = this.props.visual;

    visual[key].then();
  }
  // 属性值修改处理
  handleValueChanged(event){
    const key = event.target.id;

    const attributes = this.attributes;
    var value =  event.target.value;
    if(event.target.type === 'checkbox'){
      value = event.target.checked;
    }
    for(var i=0, il=attributes.length; i < il; i++){
      if(attributes[i].key === key){
        attributes[i].value = value;
        break;
      }
    }
    const groupedAttributes = this.groupAttributes(attributes, this.state.columns);

    if(key === 'showHelper'){
      this.setState({
        showHelper        : value,
        // attributes        : attributes,
        groupedAttributes : groupedAttributes,
      });
    }else{
      this.updateButton.current.click();  
    }
  }
  // 修改分栏数
  handleColumnChanged(event){
    if(parseInt(event.target.value) >= 1){
      const groupedAttributes = this.groupAttributes(this.attributes, event.target.value);
      this.setState({
        groupedAttributes : groupedAttributes,
        columns           : parseInt(event.target.value)
      });
    }
    else{
      const groupedAttributes = this.groupAttributes(this.attributes, 1);
      this.setState({
        groupedAttributes: groupedAttributes,
        columns : 1
      });
    }
  }
  // // 更新画布属性
  // updateCanvas(event){
  //   const attributes = this.attributes;
  //   for(var i=0, il=attributes.length; i < il; i++){
  //     const key = attributes[i].key;
  //     this.props.visual[key] = attributes[i].value;
  //   }

  //   this.props.visual.update();
  // }

  // 更新可视化界面
  updateVisual(){
    this.props.visual.updateVisual(this.attributes);
  }
  // 创建属性输入控件
  createAtrributeInput(){
    if(!this.state.sortedByGroup){
      return this.attributes.map((item, key)=>
          <div className='row' key={key}>
            <div className='cell'>{item.key}</div>
            <div className='cell'>
              {this.createInput(item)}
            </div>
          </div>)
    }
    else{
      // const groupedAttributes = this.groupAttributes();

      return this.state.groupedAttributes.map((item, key)=>
        <div className='row' key={key}>
          {item.map((group, key1)=>
            <div className='cell-border' key={key1}>
              <div className='table'>
                <div className='row'>
                  <div className='cell-underline'>{group.group}</div>
                </div>
                {group.children.map((child, key2)=>
                  <div className='row' key={key2}>
                    <div className='cell'>{child.type !== 'promise'?child.key:''}</div>
                    <div className='cell'>{this.createInput(child)}</div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      );
    }
  }
  // 创建输入控件
  createInput(attribute){
    switch(attribute.type){
      case 'number':
        return <input type='number' readOnly={attribute.readOnly}
          id={attribute.key} value={attribute.value} 
          onChange={this.handleValueChanged}></input>;
      case 'string':
        return <input type='text' readOnly={attribute.readOnly}
          id={attribute.key} value={attribute.value} 
          onChange={this.handleValueChanged}></input>;
      case 'boolean':
        return <input type='checkbox' readOnly={attribute.readOnly}
          id={attribute.key} checked={attribute.value} 
          onChange={this.handleValueChanged}></input>;
      case 'color':
        return <input type='color' readOnly={attribute.readOnly}
          id={attribute.key} value={attribute.value} 
          onChange={this.handleValueChanged}></input>;
      case 'lineStyle':
        return <select id={attribute.key} readOnly={attribute.readOnly}
        value={attribute.value} onChange={this.handleValueChanged}>
          <option>dashed</option>
          <option>solid</option>
        </select>;
      case 'textAlign':
        return <select id={attribute.key} readOnly={attribute.readOnly}
        value={attribute.value} onChange={this.handleValueChanged}>
          <option>left</option>
          <option>center</option>
          <option>right</option>
        </select>;
      case 'verticalAlign':
        return <select id={attribute.key} readOnly={attribute.readOnly}
        value={attribute.value} onChange={this.handleValueChanged}>
          <option>top</option>
          <option>middle</option>
          <option>bottom</option>
        </select>;
      case 'promise':
        return <button id={attribute.key} readOnly={attribute.readOnly} onClick={this.handleButtonClicked}>{attribute.key}</button>
      default:
        return <input type='text' readOnly={attribute.readOnly}
          id={attribute.key} value={attribute.value} 
          onChange={this.handleValueChanged}></input>;
    }
  }
  // 更新属性列表
  updateAttributes(){
    return (
      <div>
        <b>属性列表：</b>
        <label>分栏：<input type='number' value={this.state.columns} onChange={this.handleColumnChanged.bind(this)} ></input></label>
        <div className='table'>
          {this.createAtrributeInput()}
          <div className='row'>
            <div className='cell'>
              <button onClick={this.initAttributes.bind(this)} ref={this.refreshButton}>刷新</button>
              <button onClick={this.updateVisual} ref={this.updateButton}>更新</button>
            </div>
          </div>
          
        </div>
      </div>
    );
  }

  render(){
    return (
    <div className='div-hcenter'>
      <div>
        <label>{this.state.showHelper?'隐藏配置':'显示配置'}</label>
        <input type='checkbox' id='showHelper' checked={this.state.showHelper} onChange={this.handleValueChanged}></input>
      </div>
      {this.state.showHelper?this.updateAttributes():''}
    </div>);   
  }
}

export default VisualHelper;